package com.monkey.luffer.springboot.demo.basis.thread;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author dengkaibing
 * @Description
 * @Date 2024/8/7 23:24
 **/
public class ThreadPrint {


    public static void main(String[] args) throws InterruptedException {
        AtomicBoolean flagA = new AtomicBoolean(true);
        AtomicBoolean flagB = new AtomicBoolean(false);
        AtomicBoolean flagC = new AtomicBoolean(false);

        Object e = new Object();
        Thread a = new Thread(() -> {
            synchronized (e) {
                int count = 0;
                do {
                    e.notifyAll();
                    if (flagA.get()) {
                        count = count + 1;
                        System.out.println("A"+count);
                        flagB.set(true);
                        flagC.set(false);
                        flagA.set(false);

                    }
                    try {
                        e.wait();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }

                } while (count < 100);
                System.out.println("A thread is end");
                e.notifyAll();

            }

        });
        Thread b = new Thread(() -> {
            synchronized (e) {
                int count = 0;
                do {
                    e.notifyAll();
                    if (flagB.get()) {
                        count = count + 1;
                        System.out.println("B"+count);
                        flagC.set(true);
                        flagA.set(false);
                        flagB.set(false);
                    }
                    try {
                        e.wait();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }

                } while (count < 100);
                System.out.println("B thread is end");
                e.notifyAll();
            }

        });
        Thread c = new Thread(() -> {
            synchronized (e) {
                int count = 0;
                do {
                    e.notifyAll();
                    if ((flagC.get())) {
                        count = count + 1;
                        System.out.println("C"+count);
                        flagA.set(true);
                        flagB.set(false);
                        flagC.set(false);
                    }
                    try {
                        e.wait();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                } while (count < 100);
                System.out.println("C thread is end");
                e.notifyAll();

            }

        });

        a.start();
        b.start();
        c.start();
        Thread.sleep(5000);

    }
}
